﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
using System.Web.UI;
using System.Web.UI.WebControls;
using OUSMS.AppLogic.BusinessLogicLayer;
using OUSMS.AppLogic.DataAccessLayer;
using OUSMS.Helpers;
namespace OUSMS
{
    public partial class AssignUserRole : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UsersBLL usersBLL = new UsersBLL();
                IQueryable<UserRoles> userRoles = usersBLL.GetUserRolesByUserID(Convert.ToInt64(Request.QueryString["UID"]));
                CheckBoxList roleList = userInfoFormView.FindControl("roleList") as CheckBoxList;
                foreach (UserRoles userRole in userRoles)
                {
                    for (int index = 0; index < roleList.Items.Count; index++)
                    {
                        if (roleList.Items[index].Value == userRole.RoleType)
                        {
                            roleList.Items[index].Selected = true;
                            break;
                        }
                    }
                }
            }
        }

        public IQueryable<Users> GetUsersByID([QueryString("UID")]long uid)
        {
            UsersBLL usersBLL = new UsersBLL();
            return usersBLL.GetUsersByID(uid);
        }

        protected void submitBtn_Click(object sender, EventArgs e)
        {
            try
            {
                UsersBLL usersBLL = new UsersBLL();
                Users userEntity = usersBLL.GetUsersByID(Convert.ToInt64(Request.QueryString["UID"])).FirstOrDefault();
                usersBLL.ClearUserRoles(userEntity);
                CheckBoxList roleList = userInfoFormView.FindControl("roleList") as CheckBoxList;
                for (int index = 0; index < roleList.Items.Count; index++)
                {
                    if (roleList.Items[index].Selected)
                    {
                        UserRoles userRole = new UserRoles();
                        userRole.RoleType = roleList.Items[index].Text;
                        userRole.UserID = userEntity.ID;
                        usersBLL.AddUserRole(userRole);
                    }
                }
                Response.Redirect("UserManageList.aspx");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                Label errorMsgLbl = userInfoFormView.FindControl("errorMsgLbl") as Label;
                errorMsgLbl.Visible = true;
                errorMsgLbl.Text = string.Format("信息提交失败，请根据下列原因进行修改或者将错误信息报告管理员：", ex.Message);
            }
        }
    }
}